<template>
  <a-modal v-model:open="openForm" width="60vw" title="支付宝资料录入" @ok="handleOk" @cancel="handleCancel">
    <a-form ref="formRef" :model="data" v-bind="formOptions" :rules="props.formType == 'view' ? {} : rules" :disabled="props.formType == 'view'">
      <a-row :gutter="16">
        <div style="width: 100%; margin-bottom: 10px; font-size: medium">
          <span>支付宝信息:</span>
        </div>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="支付宝商户账号:" name="account">
            <a-input v-model:value="data.account" placeholder="请输入支付宝商户账号" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="营业执照法人支付宝账号对应的手机号:" name="businessLicenseMobile">
            <a-input v-model:value="data.businessLicenseMobile" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <!--        <a-col class="gutter-row" :span="12">-->
        <!--          <a-form-item label="服务费率:(0.38-0.6)%" name="rate">-->
        <!--            <a-input-number style="width: 100%" v-model:value="data.rate" :min="0.38" :max="0.6" placeholder="请输入服务费率" />-->
        <!--          </a-form-item>-->
        <!--        </a-col>-->
        <!--        <a-col class="gutter-row" :span="4">-->
        <!--          <a-form-item label="签约且授权标识:" name="signAndAuth">-->
        <!--            <a-switch v-model:checked="data.signAndAuth" checked-children="是" un-checked-children="否" />-->
        <!--          </a-form-item>-->
        <!--        </a-col>-->
        <!--        <a-col class="gutter-row" :span="8">-->
        <!--          <div style="width: 100%; padding-top: 20px; color: red">-->
        <!--            <span>确认启用签约且授权标识后，表示在签约成功后，会自动进行应用授权操作</span>-->
        <!--          </div>-->
        <!--        </a-col>-->
        <div style="width: 100%; margin-bottom: 10px; font-size: medium">
          <span>联系人信息:</span>
        </div>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="联系人姓名:" name="contactName">
            <a-input v-model:value="data.contactName" placeholder="请输入联系人姓名" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="联系人手机号:" name="mobilePhone">
            <a-input v-model:value="data.mobilePhone" placeholder="请输入联系人手机号" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="联系人邮箱:" name="contactEmail">
            <a-input v-model:value="data.contactEmail" placeholder="请输入联系人邮箱" />
          </a-form-item>
        </a-col>
        <div style="width: 100%; margin-bottom: 10px; font-size: medium">
          <span>行业信息:</span>
        </div>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="营业主体类型:" name="subjectType">
            <SmartEnumSelect width="100%" v-model:value="data.subjectType" enumName="SUBJECT_TYPE_ENUM" placeholder="请选择" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="一级行业分类:" name="firstMccCode">
            <CustomSelect
              v-model:value="data.firstMccCode"
              :api="businessCategoryApi"
              :searchFlag="false"
              :queryParams="firstParams"
              @change="(value) => changeIndustry(value)"
              value-field="categoryCode"
              label-field="categoryName"
            />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="二级行业分类:" name="SecondMccCode">
            <CustomSelect
              ref="qualificationRef"
              v-model:value="data.SecondMccCode"
              :placeholder="'请先选择一级行业分类'"
              :api="businessCategoryApi"
              :query-param-key="'categoryName'"
              :queryParams="secondParams"
              value-field="categoryCode"
              label-field="categoryName"
            />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="4">
          <a-form-item label="企业特殊资质图片:" name="specialLicensePic">
            <a-upload
              v-model:file-list="data.specialLicensePic"
              :max-count="1"
              name="specialLicensePic"
              :custom-request="(file) => uploadFunc(file, 'specialLicensePic')"
              :accept="limitUpload['specialLicensePic'].fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'specialLicensePic')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <div v-if="!isUndefined(data.SecondMccCode) && specialText(data.SecondMccCode)" style="width: 100%; padding-top: 20px; color: red">
            <span>当前行业需要上传企业特殊资质图片</span>
          </div>
          <div v-else-if="!isUndefined(data.SecondMccCode)" style="width: 100%; padding-top: 20px; color: red">
            <span>当前行业无需上传企业特殊资质图片</span>
          </div>
          <div v-if="specialText(data.SecondMccCode)">详细可参考：<a :href="linkUrl" target="_blank">支付宝商家经营类目</a></div>
        </a-col>
        <div style="width: 100%; margin-bottom: 10px; font-size: medium">
          <span>营业执照信息:</span>
        </div>
        <div style="width: 100%; margin-bottom: 10px; color: red">
          <div style="width: 25%; margin-left: 25%">
            <span>个体工商户如果使用总公司或其他公司的营业执照认证需上传该授权函图片</span>
          </div>
        </div>
        <a-col class="gutter-row" :span="6">
          <a-form-item label="营业执照照片:" name="licenseCopy">
            <a-upload
              v-model:file-list="data.licenseCopy"
              name="licenseCopy"
              :max-count="1"
              :custom-request="(file) => uploadFunc(file, 'licenseCopy')"
              :accept="limitUpload['licenseCopy'].fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'licenseCopy')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="6">
          <a-form-item label="营业执照授权函图片:" name="businessLicenseAuthPic">
            <a-upload
              v-model:file-list="data.businessLicenseAuthPic"
              name="businessLicenseAuthPic"
              :max-count="1"
              :custom-request="(file) => uploadFunc(file, 'businessLicenseAuthPic')"
              :accept="limitUpload['businessLicenseAuthPic'].fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'businessLicenseAuthPic')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="营业执照号码:" name="licenseNumber">
            <a-input v-model:value="data.licenseNumber" placeholder="请输入营业执照号码" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="营业执照商户名称:" name="licenseCompanyName">
            <a-input v-model:value="data.licenseCompanyName" placeholder="请输入营业执照商户名称" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="营业执照是否长期有效:" name="longTerm">
            <div>
              <a-switch v-model:checked="data.longTerm" checked-children="是" un-checked-children="否" />
              <span style="margin-left: 30px; color: red" v-if="data.longTerm">证件长期有效无需填写证件有效截至日期。</span>
            </div>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="营业执照有效期截止时间:" name="periodEnd">
            <a-date-picker class="w-full" v-model:value="data.periodEnd" :valueFormat="'YYYY-MM-DD'" :disabled="data.longTerm" />
          </a-form-item>
        </a-col>
        <div style="width: 100%; margin-bottom: 10px; font-size: medium">
          <span>商户信息:</span>
        </div>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="店铺名称:" name="shopName">
            <a-input v-model:value="data.shopName" placeholder="请输入店铺名称" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="店铺地址:" name="shopAddress1">
            <areaCascader
              @change="changeArea"
              v-model:value="data.shopAddress1"
              :queryParams="{ fAreaId: '999999999999', type: '0' }"
              :getMultiple="true"
              width="100%"
            />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="详细地址:" name="detailAddress">
            <a-input @change="changeArea" v-model:value="data.detailAddress" placeholder="请输入详细地址" />
          </a-form-item>
        </a-col>

        <!--        <a-col class="gutter-row" :span="12">-->
        <!--          <a-form-item label="订单授权凭证" name="orderTicket">-->
        <!--            <a-input v-model:value="data.orderTicket" placeholder="请输入订单授权凭证" />-->
        <!--          </a-form-item>-->
        <!--        </a-col>-->

        <a-col class="gutter-row" :span="6">
          <a-form-item label="店铺门头照图片:" name="shopSignBoardPic">
            <a-upload
              v-model:file-list="data.shopSignBoardPic"
              name="shopSignBoardPic"
              :max-count="1"
              :custom-request="(file) => uploadFunc(file, 'shopSignBoardPic')"
              :accept="limitUpload['shopSignBoardPic'].fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'shopSignBoardPic')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="6">
          <a-form-item label="店铺内景图片" name="shopScenePic">
            <a-upload
              v-model:file-list="data.shopScenePic"
              name="shopScenePic"
              :max-count="1"
              :custom-request="(file) => uploadFunc(file, 'shopScenePic')"
              :accept="limitUpload['shopScenePic'].fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'shopScenePic')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <template #footer>
      <a-button key="back" @click="handleCancel"> 取消 </a-button>
      <a-button key="submit" type="primary" @click="handleOk" v-if="props.formType != 'view'"> 提交 </a-button>
    </template>
  </a-modal>
</template>
<script setup name="AlipayForm">
  import { computed, onMounted, reactive, ref, watch } from 'vue'
  import { message, Upload } from 'ant-design-vue'
  import areaCascader from '/@/components/business/b-operation/area-cascader/index.vue'
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { businessCategoryApi } from '/src/api/business/b-merchant/regist/business-category.js'
  import { alipayRegistApi } from '/src/api/business/b-merchant/regist/alipay-regist-api.js'
  import { isUndefined, cloneDeep, isEmpty } from 'lodash'
  import { convertPathsToFiles, getSelectedOptions, getObjValue } from '/@/utils/common.js'
  import { myUpload } from '/@/utils/myUpload'

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    formData: {
      type: Object,
      default: () => {
        return {}
      },
    },
    // 表单类型 add/update/view
    // add: 新增, update: 编辑,view: 查看
    formType: {
      type: String,
      default: 'add',
    },
    formOptions: {
      type: Object,
      default: () => {
        return {
          layout: 'vertical',
          name: 'basic',
          autocomplete: 'off',
        }
      },
    },
    params: {
      type: Object,
      default: () => {
        return {}
      },
    },
  })

  const linkUrl = ref('https://opendocs.alipay.com/common/02khjv')

  const emit = defineEmits(['update:open', 'ok'])
  const openForm = computed({ get: () => props.open, set: (val) => emit('update:open', val) })

  const rules = ref({
    account: [{ required: true, message: '支付宝商户账号不能为空!' }],
    businessLicenseMobile: [{ required: true, message: '营业执照法人支付宝账号对应的手机不能为空!' }],
    rate: [{ required: true, message: '服务费率不能为空!' }],
    contactName: [{ required: true, message: '联系人姓名不能为空!' }],
    mobilePhone: [{ required: true, message: '联系人手机号不能为空!' }],
    contactEmail: [{ required: true, message: '联系人邮箱不能为空!' }],
    subjectType: [{ required: true, message: '营业主体类型不能为空!' }],
    firstMccCode: [{ required: true, message: '一级行业分类不能为空!' }],
    SecondMccCode: [{ required: true, message: '二级行业分类不能为空!' }],
    // specialLicensePic: [{ required: true, message: '企业特殊资质图片不能为空!' }],
    licenseCopy: [{ required: true, message: '营业执照照片不能为空!' }],
    // businessLicenseAuthPic: [{ required: true, message: '营业执照授权函图片不能为空!' }],
    licenseNumber: [{ required: true, message: '营业执照号码不能为空!' }],
    periodEnd: [
      {
        validator: (rule, value, callback) => {
          if (data.value.longTerm) {
            //提示不需要填
            return Promise.resolve()
          } else {
            if (value) {
              return Promise.resolve()
            } else {
              return Promise.reject(new Error('证件有效期截止时间不能为空'))
            }
          }
        },
        trigger: ['blur', 'change'],
      },
    ],
    shopName: [{ required: true, message: '店铺名称不能为空!' }],
    shopAddress1: [{ required: true, message: '店铺地址不能为空!' }],
    detailAddress: [{ required: true, message: '详细地址不能为空!' }],
    shopSignBoardPic: [{ required: true, message: '店铺门头照图片不能为空!' }],
    shopScenePic: [{ required: true, message: '店铺内景图片不能为空!' }],
    licenseCompanyName: [{ required: true, message: '营业执照商户名称不能为空!' }],
  })
  const formRef = ref()
  const initData = {
    licenseCompanyName: undefined,
    account: undefined,
    businessLicenseMobile: undefined,
    rate: undefined,
    signAndAuth: false,
    subjectType: undefined,
    contactName: undefined,
    merchantId: undefined,
    shopAddress1: [],
    shopAddress: [],
    mobilePhone: undefined,
    contactEmail: undefined,
    firstMccCode: undefined,
    SecondMccCode: undefined,
    specialLicensePic: [],
    licenseCopy: [],
    businessLicenseAuthPic: [],
    licenseNumber: undefined,
    longTerm: false,
    periodEnd: undefined,
    shopName: undefined,
    detailAddress: undefined,
    shopSignBoardPic: [],
    shopScenePic: [],
  }
  const data = ref(cloneDeep(initData))
  const limitUpload = {
    specialLicensePic: {
      fileType: ['.jpg', '.jpeg', '.png', '.bmp', '.gif'],
      fileSize: 5,
    },
    licenseCopy: {
      fileType: ['.jpg', '.jpeg', '.png', '.bmp', '.gif'],
      fileSize: 5,
    },
    businessLicenseAuthPic: {
      fileType: ['.jpg', '.jpeg', '.png', '.bmp', '.gif'],
      fileSize: 5,
    },
    shopSignBoardPic: {
      fileType: ['.jpg', '.jpeg', '.png', '.bmp', '.gif'],
      fileSize: 5,
    },
    shopScenePic: {
      fileType: ['.jpg', '.jpeg', '.png', '.bmp', '.gif'],
      fileSize: 5,
    },
  }
  const beforeUpload = (file, fileList, type) => {
    // 校检文件类型
    if (limitUpload[type].fileType.length) {
      const fileExt = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      const isTypeOk = limitUpload[type].fileType.includes(fileExt)
      if (!isTypeOk) {
        message.warning(`文件格式不正确, 请上传${limitUpload[type].fileType.toString().replace(/\./g, '').replace(/,/g, '、')}格式文件!`)
        return false || Upload.LIST_IGNORE
      }
    }

    // 校检文件大小
    if (limitUpload[type].fileSize) {
      const isLt = file.size / 1024 / 1024 < limitUpload[type].fileSize
      if (!isLt) {
        message.warning(`上传文件大小不能超过 ${limitUpload[type].fileSize} MB!`)
        return false || Upload.LIST_IGNORE
      }
    }

    return true
  }

  // 上传文件自定义的方法
  const uploadFunc = async (file, fieldName) => {
    // console.log('file==>', file)
    // 确保获取到文件对象
    const fileObj = file.file
    if (!fileObj) {
      return
    }
    const response = await myUpload(file)
    console.log('response==>', response)
    let arr = getObjValue(data.value, fieldName).map((item) => {
      if (item.uid === fileObj.uid) {
        message.success(`${fileObj.name} 上传成功`)
        return response
      }
      return item
    })
    setObjValue(data.value, fieldName, arr)
  }

  const validateForm = async () => {
    let isValid = false
    try {
      await formRef.value.validate()
      isValid = true
    } catch (error) {
      message.warning(error.errorFields[0].errors)
      isValid = false
    }
    return isValid
  }
  const handleOk = () => {
    // open.value = false
    validateForm().then((isValid) => {
      if (isValid) {
        const param = { ..._.cloneDeep(data.value), ..._.cloneDeep(props.params) }
        param.mccCode = data.value.firstMccCode.toString() + '_' + data.value.SecondMccCode.toString()
        param.specialLicensePic = getUrlString(data.value.specialLicensePic)
        param.businessLicenseAuthPic = getUrlString(data.value.businessLicenseAuthPic)
        param.licenseCopy = getUrlString(data.value.licenseCopy)
        param.shopSignBoardPic = getUrlString(data.value.shopSignBoardPic)
        param.shopScenePic = getUrlString(data.value.shopScenePic)
        if (props.formType === 'add') {
          alipayRegistApi.insert(param).then(() => {
            message.success('新增成功')
            resetForm()
            emit('ok', data.value)
            openForm.value = false
          })
        } /* else if (props.formType === 'update') {
          registUpdate(param).then(() => {
            message.success('修改成功')
            resetForm()
            emit('ok', data.value)
          })
        } */
      }
    })
  }

  const handleCancel = () => {
    openForm.value = false
    resetForm()
    // open.value = false
  }
  const resetForm = () => {
    // 重置表单数据
    data.value = cloneDeep(initData)
    // Object.assign(data.value, cloneDeep(initData))
    // 重置表单的 UI 状态
    formRef.value.resetFields()
    // 重置上传组件的文件列表
    const uploadFields = ['specialLicensePic', 'licenseCopy', 'businessLicenseAuthPic', 'shopSignBoardPic', 'shopScenePic']
    uploadFields.forEach((field) => {
      data.value[field] = null
    })
  }

  const submitAddress = () => {
    let { detailAddress, shopAddress1 } = data.value
    data.value.shopAddress = {
      countryCode: shopAddress1[0],
      provinceCode: shopAddress1[1],
      cityCode: shopAddress1[2],
      districtCode: shopAddress1[3],
      detailAddress,
    }
  }
  const qualificationRef = ref(null)

  const specialText = (selectedValue) => {
    const option = getSelectedOptions(selectedValue, qualificationRef)
    //如果option里面有specialQualifications就返回true，否则返回false
    return option && 'specialQualifications' in option
  }

  const changeArea = () => {
    submitAddress()
  }
  const firstParams = computed(() => {
    return {
      pCategoryCode: '000000',
      channelType: props.params.channelType,
    }
  })
  const secondParams = computed(() => {
    return {
      pCategoryCode: data.value.firstMccCode ? data.value.firstMccCode : 'unknown',
      channelType: props.params.channelType,
    }
  })
  // 一级行业改变
  const changeIndustry = (val) => {
    data.value.SecondMccCode = undefined
    // secondParams.pCategoryCode = val ? val : 'unknown'
  }

  const getUrlString = (fileList) => {
    //判断数组长度，如果为1则返回第一个元素的url，如果为空则返回空字符串，如果大于1则返回所有元素的url的数组
    if (fileList && fileList.length === 1) {
      return fileList[0].url
    } else {
      return undefined
    }
  }

  function show(rowData) {
    if (rowData && !isEmpty(rowData)) {
      Object.assign(data.value, rowData)
    }
    console.log('rowData', rowData)

    data.value.specialLicensePic = convertPathsToFiles(rowData.specialLicensePic, '企业特殊资质图片')
    data.value.licenseCopy = convertPathsToFiles(rowData.licenseCopy, '营业执照照片')
    data.value.businessLicenseAuthPic = convertPathsToFiles(rowData.businessLicenseAuthPic, '营业执照授权函图片')
    data.value.shopSignBoardPic = convertPathsToFiles(rowData.shopSignBoardPic, '店铺门头照图片')
    data.value.shopScenePic = convertPathsToFiles(rowData.shopScenePic, '店铺内景图片')
  }
  watch(
    [() => props.formData, () => props.open],
    (newVal) => {
      if ((props.formType == 'update' || props.formType == 'view') && props.open) {
        show(cloneDeep(newVal[0]))
        console.log('data===>', data.value)
      }
    },
    { deep: true, immediate: true },
  )
  // 在组件挂载时初始化地址选项
  onMounted(() => {})
  defineExpose({
    formRef,
  })
</script>
<style lang="scss" scoped></style>
